package com.diy.sigmund.diycommon.spring.config.util;

import com.diy.sigmund.diycommon.entity.base.exception.DiyRuntimeException;
import com.diy.sigmund.diycommon.entity.enumerate.ResponseEnum;
import com.diy.sigmund.diycommon.util.json.JacksonUtil;
import java.util.Objects;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

/**
 * @author ylm-sigmund
 * @since 2021/8/26 17:23
 */
@Component
public class RestTemplateUtil {

    @Resource
    private RestTemplate customRestTemplate;

    private static final Logger log = LoggerFactory.getLogger(RestTemplateUtil.class);

    public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType,
            Object... uriVariables) throws RestClientException {
        final T result = customRestTemplate.postForObject(url, request, responseType, uriVariables);
        log.info("RestTemplate调用返回对象={}", JacksonUtil.toJson(result));
        if (Objects.isNull(result)) {
            throw new DiyRuntimeException(ResponseEnum.INTERNAL_SERVER_BUSY);
        }
        return result;
    }
}
